package edu.ynu.se.xiecheng.achitectureclass.common.config;

import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .csrf().disable()  // 禁用 CSRF 防护
                .authorizeRequests()
                .antMatchers("/camera_images/**").permitAll()
                .antMatchers("/user/login", "/user/register").permitAll()  // 放行登录和注册
                .antMatchers("/sensor/**").permitAll()// 放行 sensor 路径
                .antMatchers("/camera/**").permitAll()
                .anyRequest().authenticated()  // 其他请求需要认证
                .and()
                .formLogin()  // 使用表单登录
                .permitAll()
                .and()
                .logout().permitAll();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("user").password(passwordEncoder().encode("password")).roles("USER");
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
    @Bean
    public AuthenticationFailureHandler authenticationFailureHandler() {
        return (request, response, exception) -> {
            // 返回错误响应，不进行重定向
            response.setStatus(401);  // 设置 HTTP 状态码为 401 Unauthorized
            response.getWriter().write("{\"error\": \"Invalid credentials\"}");  // 自定义错误消息
        };
    }
}
